import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/Home.vue'),
      meta: { requiresAuth: true } // 该url径必须是登录用户才能访问
    },   
    {
      path: '/user',
      name: 'user',
      component: () => import('@/views/User.vue'),
      meta: { requiresAuth: true } // 该url径必须是登录用户才能访问
    },   
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/',
      name: 'index',
      component: () => import('@/views/Index.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/Register.vue')
    },
    {
      path: '/wz',
      name: 'wz',
      component: () => import('@/views/Wz.vue')
    },
    
    {
      path: '/mesg',
      name: 'mesg',
      component: () => import('@/views/Mesg.vue')
    }

  ]
});

router.beforeEach((to, from, next) => {
  // 路由全局前置守卫
  const isAuthenticated = localStorage.getItem('auth') === 'true';
  console.log(isAuthenticated);
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    // 检查目标路由（to）的配置中是否包含meta.requiresAuth: true这个属性。该路由需要用户登录才能访问，否则跳转登录页面
    next('/login');
  } else {
    next();
  }
})

export default router
